﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using MISAPP.Classify.Service;

public partial class View_MIS_SquaredUPLoad : ViewMatrix
{
    protected enum flType { XLS,PPT,TXT }
    
    //public string name_collect = string.Empty;
    //public string value_collect = string.Empty;

    string uploadFile = string.Empty;
    protected void Page_Load(object sender, EventArgs e)
    {
        Utility.LoadJquery(this, "jquery", "jquery");
        Utility.LoadJquery(this, "jqueryUI", "jqueryUI");

        hdn_name_collect.Value = 
            Utility.GetWebConfigAppSettingsValue("hdn_name_collect");
        
        hdn_value_collect.Value =
            Utility.GetWebConfigAppSettingsValue("hdn_value_collect");

    }

    protected void btnBonus_Click(object sender, EventArgs e)
    {
        
        this.Service_Bonus_collect("BONUS", "年獎員額及盈餘空間彙總 Upload 失敗!"
            , upLoadBonus, "Bonus_Space.xls");
    }

    /// <summary>
    /// 上傳文字檔用
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btnFastUpload_click(object sender, EventArgs e)
    {
        Service_Bonus_collect_temp(Service_Bonus.BonusType.BUDGET
, "預算執行分析 Upload 失敗!", uploadFast, "BUDGET.xls");        
    }

    protected void btnFastUploadQ1_click(object sender, EventArgs e)
    {
        Service_Bonus_collect_temp(Service_Bonus.BonusType.Q1
, "季追蹤 Upload 失敗!", upLoadQ1, "BU追蹤表100Q1.xls");        
    }

    protected void newBonusCollect(FileUpload p_upload,string p_faile_str,
        Service_Bonus.BonusType p_bonusType, string p_filename)
    {
        try
        {
            if (!saveAS(p_upload, flType.XLS))
            { return; }
            Service_Bonus bon = new Service_Bonus();

            if (bon.InsertFromXls(uploadFile, getResultValue(1)
                , getResultValue(0), p_bonusType))
            {
                string dlFile = templateToDownload(p_filename, "xls");
                //bon.FillSquared2Xls(dlFile);
                lblResult.Text = string.Format("上傳完成 新檔名{0}", uploadFile);
                showDownLoadFile(dlFile);
            }
            else
            {
                throw new Exception("Upload 失敗!");
            }
        }
        catch (Exception ex)
        {
            lblResult.Text = ex.Message;
        }
    }
    /* 2013-12-24 先mark 這個版本應該是快速版
    protected void btnUPLoad_Click(object sender, EventArgs e)
    {
        try
        {
            if (!saveAS(upLoad, flType.XLS))
            { return; }
            Service_Squared servSeq = new Service_Squared();
            if (servSeq.InsertFromXls(uploadFile, getResultValue(1), getResultValue(0)))
            {
                string dlFile = templateToDownload("ForDownLoad.xls", "xls");
                servSeq.FillSquared2Xls(dlFile);
                lblResult.Text = string.Format("上傳完成 新檔名{0}", uploadFile);
                showDownLoadFile(dlFile);
            }
            else
            {
                throw new Exception("Upload 失敗!");
            }
        }
        catch (Exception ex)
        {
            lblResult.Text = ex.Message;
        }
    }
    */

    protected void btnUPLoad_Click(object sender, EventArgs e)
    {
        //Response.Write(DateTime.Now.ToString());
        try
        {
            if (!saveAS(upLoad, flType.XLS))
            { return; }
            Service_Squared servSeq = new Service_Squared();
            List<Squared> seqList = servSeq.GetSquared(getResultValue(1));
            Squared_Excel seq_xls = new Squared_Excel(
                servSeq.GetSquaredCaption());
            System.Data.DataTable dt = servSeq.GetSquaredDT();
            //if (seq_xls.ReadUploadFile(uploadFile, seqList, getResultValue(0),ref dt))
            if (seq_xls.ReadUploadFile(uploadFile, seqList))
            {
                if (false == servSeq.InsertSquared(seq_xls.SquaredValue, getResultValue(0)))
                //if (false == servSeq.InsertSquared(dt))
                {
                    throw new Exception("Upload 失敗!");
                }
            }
            lblResult.Text = string.Format("上傳完成 新檔名{0}", uploadFile);
            string dlFile = templateToDownload("Template.xls", "xls");
            //seq_xls.GetSquaredResult(dlFile, servSeq);
            seq_xls.GetSquaredResult(dlFile, servSeq, true);
            showDownLoadFile(dlFile);
            seq_xls.ReleaseExcel();
        }
        catch (Exception ex)
        {
            lblResult.Text = ex.Message;
        }
        //Response.Write(DateTime.Now.ToString());
    }

    protected void btnKPI_Click(object sender, EventArgs e)
    {
        if (!saveAS(upLoadKPI,flType.XLS))
        { return; }

        Service_KPI kpi = new Service_KPI();
        List<Squared> seqList = kpi.GetKPISheet(getResultValue(1));
        Squared_Excel se = new Squared_Excel();
        se.KPISetVersion(uploadFile, seqList, kpi, getResultValue(0));
        string dlFile = templateToDownload("KPI.xls", "xls");
        showDownLoadFile(dlFile);
        se.GetKPIAll(kpi, dlFile);
        se.ReleaseExcel();
    }

    protected void btnBus_Click(object sender, EventArgs e)
    {
        presentation(Service_Presentation.PPTType.PPT經委會
            , upLoadBus);
    }

    protected void btnBus2_Click(object sender, EventArgs e)
    {
        presentation(Service_Presentation.PPTType.PPT經委會預算報告
            , upLoadBus2);
    }

    protected void btnNextYear_Click(object sender, EventArgs e)
    {
        presentation(Service_Presentation.PPTType.PPT明年度預算
            , FileUpload1);
    }

    protected void btnQ1_Click(object sender, EventArgs e)
    {
        Service_Bonus_collect("Q1", "BU追蹤表100Q1 Upload 失敗!"
            , upLoadQ1, "BU追蹤表100Q1.xls");
    }

    /// <summary>
    /// 因應新方法，所以先改取資料回去的做法，再來改上傳取資料的方法
    /// </summary>
    /// <param name="p_team"></param>
    /// <param name="p_faile_str"></param>
    /// <param name="p_upload"></param>
    /// <param name="p_filename"></param>
    protected void Service_Bonus_collect_temp(Service_Bonus.BonusType p_team, string p_faile_str
        , FileUpload p_upload, string p_filename)
    {
        if (!saveAS(p_upload, flType.XLS))
        { return; }

        Service_Bonus q1 = new Service_Bonus();
        try
        {
            if (false == q1.InsertFromXls(uploadFile
                , getResultValue(1), getResultValue(0), p_team))
            {
                throw new Exception(p_faile_str);
            }
            lblResult.Text = string.Format("上傳完成 新檔名{0}", uploadFile);
            string dlFile = templateToDownload(p_filename, "xls");
            q1.FillBonus2Xls(dlFile, p_team);
            showDownLoadFile(dlFile);

            /* 2014-02-26 這是舊版本
            //q1.FillBonus2Xls(dlFile, p_team);
            Squared_Excel seq_xls = new Squared_Excel();
            seq_xls.GetBonusResult(dlFile, q1);
            showDownLoadFile(dlFile);
            seq_xls.ReleaseExcel();
            */

        }
        catch (Exception ex)
        {
            lblResult.Text = string.Format("{0}:{1}", p_faile_str, ex.Message);
        }
    }

    protected void btnCost_Click(object sender, EventArgs e)
    {

        this.Service_Bonus_collect("COST", "營業費用BG Upload 失敗!"
           , uploadCost, "營業費用BG.xls");
    }

    /// <summary>
    /// 未來所有要用到Service_Bonus的全都用這個
    /// </summary>
    /// <param name="p_team"></param>
    /// <param name="p_faile_str"></param>
    /// <param name="p_upload"></param>
    /// <param name="p_filename"></param>
    protected void Service_Bonus_collect(string p_team ,string p_faile_str
        ,FileUpload p_upload,string p_filename)
    {
        if (!saveAS(p_upload, flType.XLS))
        { return ; }

        Service_Bonus q1 = new Service_Bonus(p_team);
        List<Squared> seqList = q1.GetBonusCell(getResultValue(1));
        Squared_Excel seq_xls = new Squared_Excel();
        if (seq_xls.ReadUploadBonus(uploadFile, seqList))
        {
            if (false == q1.Insert(seq_xls.SquaredValue, getResultValue(0)))
            {
                throw new Exception(p_faile_str);
            }
            lblResult.Text = string.Format("上傳完成 新檔名{0}", uploadFile);
            string dlFile = templateToDownload(p_filename, "xls");
            //seq_xls.GetCostResult(dlFile, q1);
            seq_xls.GetBonusResult(dlFile, q1);
            showDownLoadFile(dlFile);
            seq_xls.ReleaseExcel();
        }        
    }


    protected void presentation(Service_Presentation.PPTType p_type
        , System.Web.UI.WebControls.FileUpload upLoadCont)
    {
        if (!saveAS(upLoadCont,flType.PPT))
        { return; }
        string misGrooup = getMisGroup();
        Service_Presentation ppt = new Service_Presentation();
        ppt.InsertPresentation(misGrooup, getResultValue(0), uploadFile
            , p_type);
        string dlFile = templateToDownload("Presentation.ppt", "ppt");
        ppt.MergePresentation(dlFile, p_type);
        showDownLoadFile(dlFile);
        ppt.ReleasePPT();        
    }

    /// <summary>
    /// 要在這檢查是否目前使用者為「kueichuan.lin」，因為她一個人要上傳兩份檔案
    /// 從檔名+user_id 來檢查，再給不同的檔名
    /// </summary>
    protected string getMisGroup()
    {
        string grp = string.Empty;
        string user_id = getResultValue(0);
        if (user_id.Equals("kueichuan.lin"))
        {
            grp = uploadFile.ToUpper().IndexOf("HEAD") > 0 ? "HEAD" : "FOOT";
        }
        else
        {
            grp = getResultValue(2);
        }
        return grp;
    }

    protected void showDownLoadFile(string p_down)
    {
        linkExcel.NavigateUrl = string.Format("~/download/{0}",
               System.IO.Path.GetFileName(p_down));
        linkExcel.Text = "目前結果";    
    }


    /// <summary>
    /// 上傳預算執行分析
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btnBudget_Click(object sender, EventArgs e)
    {
        //this.Service_Bonus_collect("BUDGET", "預算執行分析 Upload 失敗!"
        //    , uploadBudget, "BUDGET.xls");

    }

    protected void btnBudgetPPT_Click(object sender, EventArgs e)
    {
        presentation(Service_Presentation.PPTType.PPT預算執行分析附件
           , uploadBudgetPPT);        
    }

    protected bool saveAS(System.Web.UI.WebControls.FileUpload upLoadCont
        , flType P_type)
    {
        //確認副檔名
        
        bool ok = false; //沒有檔案就不往下做
        uploadFile = string.Empty;
        if (upLoadCont.HasFile)
        {
            string extensStr = System.IO.Path.GetExtension(upLoadCont.FileName)
                .Substring(1);
            if (extensStr.ToUpper().Equals(P_type.ToString().ToUpper()))
            {
                uploadFile = Utility.SaveAS(upLoadCont, getResultValue(2)
                , Server.MapPath("~"));
                ok = true;
            }
            else
            { lblResult.Text = string.Format("你要上傳的檔案應該是{0}！！"
                ,P_type.ToString()) ; }
        }
        return ok;

    }

    /// <summary>
    /// 從tempload 資料夾 存到 download 去
    /// </summary>
    protected string templateToDownload(string p_name,string p_ext)
    {       
        return Utility.TemplateToDownload(Server.MapPath("~"),p_name,p_ext);
    }
}
